<template>
  <div class="CarryInfoDialog">
    <el-dialog title="接运信息维护" :visible.sync="$parent.DialogAddCarry" v-dialogDrag width="80%" @close="closeDialog()">
      <el-form :model="copytaskallInfo.transportTask" :rules="rules" :inline="true" label-width="120px" ref="Carry"
               :disabled="saveFlag">
        <el-row :gutter="5">
          <el-form-item label="预约时间：" prop="appointmentTime">
            <el-date-picker type="datetime" placeholder="选择日期" :disabled="appointmentTimeflag" format="yyyy-MM-dd HH:mm"
                            v-model="copytaskallInfo.transportTask.appointmentTime"
                            style="width: 100%;"></el-date-picker>
          </el-form-item>
          <el-form-item label="预约车型：" prop="transportCarType">
            <el-select v-model="copytaskallInfo.transportTask.transportCarTypeCode"
                       :disabled="!CarryAddFlag && !modifyFlag"
                       placeholder="请选择" class="w150"
                       @change="changeTypeCodeAsRuleItem(copytaskallInfo.transportTask.transportCarTypeCode)"
            >
              <el-option
                v-for="(item,index) in transportCarTypes"
                :key="index"
                :label="item.dataText"
                :value="item.dataCode"
                :disabled="item.disableState>0?true:false"/>
            </el-select>
          </el-form-item>
          <el-form-item label="车辆：">
            <el-select v-model="copytaskallInfo.transportTask.transportCarId" :disabled="!CarryAddFlag && !modifyFlag"
                       placeholder="请选择" class="w150"
                       onkeydown="return (event.keyCode!=8)"
                       @change="cartype(copytaskallInfo.transportTask.transportCarId)">
              <el-option
                v-for="(item,index) in car"
                :key="index"
                :label="item.carNo"
                :disabled="item.disableState>0?true:false"
                :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="接运司机：">
            <el-select v-model="copytaskallInfo.transportTask.driverUserId" :disabled="!CarryAddFlag && !modifyFlag"
                       placeholder="请选择"
                       class="w150"
                       @change="driverUser(copytaskallInfo.transportTask.driverUserId)">
              <el-option
                v-for="(item,index) in driverUsers"
                :key="index"
                :label="item.fullName"
                :disabled="item.disableState>0?true:false"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="司机电话：">
            <el-input v-model="copytaskallInfo.transportTask.driverUserTelephone"
                      :disabled="!CarryAddFlag && !modifyFlag"></el-input>
          </el-form-item>
          <el-form-item label=" 抬尸工：">
            <el-select v-model="copytaskallInfo.transportTask.transportTaskPorter"
                       :disabled="!CarryAddFlag && !modifyFlag" multiple
                       placeholder="请选择">
              <el-option
                v-for="(item,index)  in transportTaskPorters"
                :key="index"
                :label="item.fullName"
                :disabled="item.disableState>0?true:false"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="车辆用途：" prop="transportPurposeCode">
            <el-select v-model="copytaskallInfo.transportTask.transportPurposeCode"
                       @change="changePurposeAsRuleItem(copytaskallInfo.transportTask.transportPurposeCode)"
                       :disabled="!CarryAddFlag && copytaskallInfo.transportTask.charges.businessCharge.asSettled=='1'?true:false"
                       placeholder="请选择" class="w150">
              <el-option
                v-for="(item,index) in  transportPurposes"
                :key="index"
                :label="item.dataText"
                :value="item.dataCode"
                :disabled="item.disableState>0?true:false"/>
            </el-select>
          </el-form-item>
          <el-form-item label="接运地点：" prop="transportPlace">
            <el-input v-model="copytaskallInfo.transportTask.transportPlace" style="width: 534px"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="任务状态：" prop="processStateCode">
            <el-select v-model="copytaskallInfo.transportTask.processStateCode" onkeydown="return (event.keyCode!=8)"
                       placeholder="请选择" style="width: 120px;">
              <el-option
                v-for="(item,index) in processStates"
                :key="index"
                :label="item.dataText"
                :value="item.dataCode"
                :disabled="item.disableState?true:false"/>
            </el-select>
          </el-form-item>
          <el-form-item label="出车时间：">
            <el-date-picker type="datetime" placeholder="选择日期" :disabled="appointmentTimeflag" format="yyyy-MM-dd HH:mm"
                            v-model="copytaskallInfo.transportTask.departureTime" style="width: 100%;"></el-date-picker>
          </el-form-item>
          <el-form-item label="回车时间：">
            <el-date-picker type="datetime" placeholder="选择日期" :disabled="appointmentTimeflag" format="yyyy-MM-dd HH:mm"
                            v-model="copytaskallInfo.transportTask.returnTime" style="width: 100%;"></el-date-picker>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="行驶里程：">
            <el-input v-model="copytaskallInfo.transportTask.transportDistance" @keyup.native="checkNumber()"
                      @change="loadChargeWithRule()"
                      :disabled="!CarryAddFlag && copytaskallInfo.transportTask.charges.businessCharge.asSettled=='1'?true:false"
            ></el-input>
          </el-form-item>
          <el-form-item label="接运费用：">
            <el-input v-model="copytaskallInfo.transportTask.charges.businessCharge.itemCharge"
                      type="number" :readonly="true"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="接运联系人：">
            <el-input v-model="copytaskallInfo.transportTask.transportLinkman"></el-input>
          </el-form-item>
          <el-form-item label="联系人电话：" prop="transportTelephone">
            <el-input v-model="copytaskallInfo.transportTask.transportTelephone"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="规则描述：">
            <el-input type="textarea" v-model="copytaskallInfo.transportTask.ruleRemark" :readonly="true"
                      style="width: 534px;"></el-input>
          </el-form-item>

        </el-row>
        <el-row :gutter="5">
          <el-form-item label="备注：">
            <el-input type="textarea" v-model="copytaskallInfo.transportTask.remark" style="width: 534px;"></el-input>
          </el-form-item>

        </el-row>
        <div class="tablewrapper">
          <div class="table">
            <div class="title"><span>所有随车物品、服务</span>
              <!--<el-input v-model="search" placeholder="搜索物品/服务" style="width: 200px;float: right;"></el-input>-->
            </div>
            <el-table
              :data="copyGoodServices"
              :header-cell-style="{background:'rgb(246,247,251)',color:'#606266'}"
              border
              style="width: 99%;">
              <el-table-column align='center' prop="itemName" label="收费项目" sortable min-width="120"
                               column-key="serviceItemId">
              </el-table-column>
              <el-table-column
                prop="itemPrice"
                align='right'
                label="单价"
                min-width="80">
                <template slot-scope="{row,$index}">
                  <input class="edit-cell" v-if="row.asFixPrice !=1" type="number"
                         onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null" v-model="row.itemPrice">
                  <label class="edit-cell" v-if="row.asFixPrice ==1">{{ row.itemPrice }}</label>
                </template>
              </el-table-column>
              <el-table-column
                prop="itemNumber"
                align='right'
                label="数量"
                min-width="50">
                <template slot-scope="{row,$index}">
                  <input class="edit-cell"
                         onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null"
                         v-model="row.itemNumber">
                </template>
              </el-table-column>
              <el-table-column
                prop="itemUnit"
                align='center'
                label="单位"
                min-width="50">
              </el-table-column>
              <el-table-column
                prop="itemCharge"
                align='right'
                label="总金额"
                min-width="80">
                <template slot-scope="{row,$index}"
                          v-if="Number(row.itemPrice)>=0 &&Number(row.itemNumber)>=0&&Number(row.discountCharge)>=0">
                  {{
                    Number((row.itemPrice.match(/^\d+(?:.\d{0,2})?/)) * (row.itemNumber.match(/^\d+(?:.\d{0,2})?/))).toFixed(2)
                  }}
                </template>
              </el-table-column>
              <el-table-column
                prop="discountCharge"
                align='right'
                label="优惠"
                min-width="50">
                <template slot-scope="{row,$index}">
                  <!--根据值来判断是否可以修改-->
                  <input class="edit-cell" onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null"
                         v-model="row.discountCharge">
                </template>
              </el-table-column>
              <el-table-column
                label="物品剩余"
                align="center"
                prop="itemSurplusNum">
              </el-table-column>
              <el-table-column
                label="操作"
                align='center'
                min-width="100">
                <template slot-scope="{row,$index}">
                  <el-button
                    @click.native.prevent="AddRow($index)"
                    type="text"
                    size="small">
                    追加
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--<p class="tablecont">单价、数量、优惠三个字段值允许工作人员直接更改，更改完成后可通过“追加”按钮进行费用追加。</p>-->
          </div>
          <div class="table">
            <h3 class="title">已追加随车物品、服务</h3>
            <el-table :fit="true"
                      :data="copytaskallInfo.transportTask.charges.goodsServices"
                      :header-cell-style="{background:'rgb(246,247,251)',color:'#606266'}"
                      border
                      style="width: 99%;">
              <el-table-column align='center' prop="itemName" sortable label="收费项目" min-width="120">
              </el-table-column>
              <el-table-column
                prop="itemPrice"
                align='right'
                label="单价"
                min-width="80">
              </el-table-column>
              <el-table-column
                prop="itemNumber"
                align='right'
                label="数量"
                min-width="50">
              </el-table-column>
              <el-table-column
                prop="itemUnit"
                align='center'
                label="单位"
                min-width="50">
              </el-table-column>
              <el-table-column
                prop="itemCharge"
                align='right'
                label="项目金额"
                min-width="80">
              </el-table-column>
              <el-table-column
                prop="discountCharge"
                align='right'
                label="优惠"
                min-width="50">
              </el-table-column>
              <el-table-column
                prop="benefitCharge"
                align='right'
                label="减免"
                min-width="50">
              </el-table-column>
              <el-table-column
                prop="asSettled"
                align='center'
                label="结算状态"
                width="100">
                <template slot-scope="{row,$index}">
                  <span v-if="row.asSettled==0">未结算</span>
                  <span v-else-if="row.asSettled==1">已结算</span>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align='center'
                width="100">
                <template slot-scope="{row,$index}">
                  <el-button v-if="row.asSettled==0"
                             @click.native.prevent="deleteRow($index,copytaskallInfo.transportTask.charges.goodsServices)"
                             type="text"
                             size="small">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--<p class="tablecont">此区域费用信息不允许更改，仅未结算的费用可以进行删除操作。-->
            <!--无论是新追加的费用还是删除的费用，均在保存操作后生效。-->
            <!--</p>-->
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: right">
        <el-button type="primary" @click="Save()" :disabled="saveFlag">保 存</el-button>
        <el-button type="primary" plain @click="$parent.DialogAddCarry = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as Type from '@/api/service'
import {dataFormate, dataFormatetmd} from '@/utils/index'
import {toFixed} from "@/utils/tofixed"

export default {
  name: "CarryInfoDialog",
  props: {
    DialogAddCarry: {
      type: Boolean
    },
    taskallInfo: {
      type: Object,
      default: function () {
        return {
          "transportTask": {
            id: 0,
            businessCode: "",
            appointmentTime: "",
            transportCarTypeCode: "",
            transportCarId: "",
            carNo: "",
            driverUserId: "",
            driverUserName: '',
            driverUserTelephone: '',
            transportTaskPorter: [],
            transportPurposeCode: "",
            transportPlace: '',
            processStateCode: "",
            departureTime: '',
            returnTime: '',
            transportDistance: 0,
            remark: '',
            calculateRule: '',
            version: 0,        //数据版本，新增时传0
            transportLinkman: '',//联系人
            transportTelephone: '',//联系方式
            rule_number: "",
            rule_unit: "",
            rule_code: "",
            rule_remark: "",
            charges: {
              businessCharge: {       //用于计算
                id: 0,
                serviceItemId: 0,
                itemPrice: 1,
                itemNumber: 1,
                itemUnit: "m",
                itemCharge: 1,
                discountCharge: 0,
                benefitCharge: 0,
                realityCharge: 0,
                asSettled: 1,
                version: 0,
              },
              goodsServices: [{
                id: 0,
                serviceItemId: 0,
                itemPrice: 1,
                itemNumber: 1,
                itemUnit: "m",
                itemCharge: 1,
                discountCharge: 0,
                benefitCharge: 0,
                realityCharge: 1,
                asSettled: 1,
                version: 0,
              }],
              deleteIds: [{id: 0, version: 0}]//删除明细id与version
            },
          },

        }
      }
    },
    CarryAddFlag: {    //true 为新增
      type: Boolean
    }, ruleItems: {   //规则
      type: Array
    },//传的字典
    OldCarId: {
      type: Number//旧车辆id 不用传null或不传参数
    },
    transportCarTypes: {   //预约车型名称集合
      type: Array
    },
    cars: {   //车辆牌号名称集合
      type: Array
    },
    driverUsers: {   //司机名称集合
      type: Array
    },
    transportTaskPorters: {   //抬尸工集合
      type: Array
    },
    transportPurposes: {   //车辆用途名称集合
      type: Array
    },
    processStates: {   //接运状态集合
      type: Array
    },
    dicts: {
      transport_car_type: [],//车辆类型
      transport_car_use: []//用途
    }
  },
  data() {
    return {
      saveFlag: false,     //保存过程中不可更改,true为正在保存
      rules: {
        appointmentTime: [
          {required: true, message: '请选择预约时间', trigger: 'blur'},
        ],
        transportCarType: [
          {required: true, message: '请选择预约车型', trigger: 'blur'},
        ],
        transportPlace: [
          {required: true, message: '请输入接尸地点', trigger: 'blur'},
        ],
        processStateCode: [
          {required: true, message: '请选择任务状态', trigger: 'blur'},
        ],
        transportTelephone: [
          {required: true, message: '请填写联系电话', trigger: 'blur'},
        ],
        transportPurposeCode: [
          {required: true, message: '请选择车辆用途', trigger: 'blur'},
        ],
      },
      search: "",
      ruleForm: {},
      car: [],
      copyGoodServices: [],
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      formLabelWidth: '120px',
      dictionary: {},      //字典
      btnPermisson: {},
      copytaskallInfo: this.taskallInfo,//传过来的接运信息
      appointmentTimeflag: false,
      ruleItem: {},//收费规则
      //传的字典
      copydicts: this.dicts,//传过来的字典值
      modifyFlag: false,//修改的标志
      onpresscTime: 0,  //  阻止短时间内连续点击
      submitFlag: true//可提交标记
    }
  },
  watch: {
    '$parent.DialogAddCarry'() {
      this.copytaskallInfo = this.taskallInfo
      this.copyGoodServices = JSON.parse(JSON.stringify(this.taskallInfo.serviceItems.use_in_transport_task));   //复制
      /*根据车型加载车辆*/
      if (this.copytaskallInfo.transportTask.transportCarTypeCode) {
        this.loadTransportCar(this.copytaskallInfo.transportTask.transportCarTypeCode, this.OldCarId)
      }
      // this.copytaskallInfo.transportTask.charges.businessCharge.itemCharge=''
      //替换时间格式
      if (!this.CarryAddFlag) {
        if (typeof (this.copytaskallInfo.transportTask.appointmentTime) == "string" && this.copytaskallInfo.transportTask.appointmentTime.indexOf("-") > -1) {
          this.copytaskallInfo.transportTask.appointmentTime = this.copytaskallInfo.transportTask.appointmentTime.replace(/-/g, "/");
        }
        if (typeof (this.copytaskallInfo.transportTask.departureTime) == "string" && this.copytaskallInfo.transportTask.departureTime.indexOf("-") > -1) {
          this.copytaskallInfo.transportTask.departureTime = this.copytaskallInfo.transportTask.departureTime.replace(/-/g, "/");
        }
        if (typeof (this.copytaskallInfo.transportTask.returnTime) == "string" && this.copytaskallInfo.transportTask.returnTime.indexOf("-") > -1) {
          this.copytaskallInfo.transportTask.returnTime = this.copytaskallInfo.transportTask.returnTime.replace(/-/g, "/");
        }
        /*排查出已预约的状态字，编辑已预约状态信息可以更改*/
        let yiyuyue = -1;
        if (this.copytaskallInfo.dicts.transport_car_task_status && this.copytaskallInfo.dicts.transport_car_task_status.length) {
          this.copytaskallInfo.dicts.transport_car_task_status.forEach(item => {
            if (item.dataText.indexOf("已预约") > -1) {
              yiyuyue = item.dataCode
              return
            }
          })
          if (yiyuyue == this.copytaskallInfo.transportTask.processStateCode) {
            this.modifyFlag = true
          }
        }
      }
      this.$parent.DialogAddCarry = this.DialogAddCarry;
      if (this.$parent.DialogAddCarry == false) {
        this.ruleForm = {}
        this.modifyFlag = false
        this.$nextTick(() => {
          this.$refs.Carry.resetFields();
        })
      }
    }
  },
  methods: {
    //验证里程
    checkNumber() {
      // 先把非数字的都替换掉，除了数字和.
      let obj = this.copytaskallInfo.transportTask.transportDistance;
      this.copytaskallInfo.transportTask.transportDistance = this.checkNum(obj, 2);
    },//验证数字的通用方法 obj为要验证的数据，n为保留几位小数。
    checkNum(obj, n) {
      // 先把非数字的都替换掉，除了数字和.
      obj = obj.replace(/[^\d.]/g, '');
      // 必须保证第一个为数字而不是.
      obj = obj.replace(/^\./g, '');
      // 保证只有出现一个.而没有多个.
      obj = obj.replace(/\.{2,}/g, '');
      // 保证.只出现一次，而不能出现两次以上
      obj = obj.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
      let index = -1
      for (let i in obj) {
        if (obj[i] === '.') {
          index = i
        }
        if (index !== -1) {
          //保留两位小数
          if (i - index > n) {
            obj = obj.substring(0, obj.length - 1)
          }
        }
      }
      //返回验证后的结果
      return obj;
    },
    //车辆变化触发接运司机变化
    cartype(code) {    //此code wei driverUserId
      if (this.car.length > 0) {
        this.car.forEach((item) => {
          if (item.id == code) {
            this.copytaskallInfo.transportTask.driverUserId = item.driverUserId;
            this.driverUser(item.driverUserId)
          }
        })
      }

    },
    //根据车型加载车辆
    loadTransportCar(code, oldCarId) {
      let load_this = this;
      let postData = {
        //车辆类型编码
        "typeCode": code,
        "oldCarId": oldCarId
      }
      Type['loadtransportcarwithtypecode'](postData).then(response => {
        let result = response;
        const {data} = result
        if (!data) {
          load_this.$message('加载信息出错.')
        }
        //数据读取成功
        load_this.car = data
        //原车型不为空，默认加载原来车型的数据
        if (oldCarId != null) {
          load_this.copytaskallInfo.transportTask.transportCarId = load_this.OldCarId
          //加载合并后的车型
          load_this.car = load_this.pushCarDataArray(load_this.car, load_this.cars);
        }

      }).catch(error => {
        load_this.$message(error)
      })
    },//查询对象id是否在数据集合中
    getFlagById(data, item) {
      let flag = false;
      if (data && data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          if (data[i].id == item.id) {
            flag = true;
            break;
          }
        }
      }
      //返回结果
      return flag;
    },
    //合并初次加载车辆
    pushCarDataArray(data, dataOld) {
      //判断data及code及名称不能为空
      if (data && dataOld && data.length > 0 && dataOld.length > 0) {
        //定义新数据数组
        let addArray = [];
        for (let m = 0; m < dataOld.length; m++) {
          //获得旧数据的明细
          let itemOld = dataOld[m];
          if (itemOld && itemOld.id && itemOld.carNo) {
            let flag = this.getFlagById(data, itemOld);
            //不存在
            if (!flag) {
              let itemDisabled = {
                id: itemOld.id,
                carNo: itemOld.carNo,
                disableState: 1
              }
              addArray.push(itemDisabled)
            }
          }
        }

        //如果有新数据项，合并新数据项
        if (addArray && addArray.length > 0) {
          for (let i = 0; i < addArray.length; i++) {
            data.push(addArray[i]);
          }
        }
      }
      //返回合并后的新数据项
      return data;
    },
    //根据车辆类型加载车辆
    changeTypeCodeAsRuleItem(code) {
      if (!code) {
        this.$message('code值无效')
        return;
      }
      //判断并选择费用
      //清空用途
      this.copytaskallInfo.transportTask.transportPurposeCode = '';
      /*清空接运费用*/
      this.copytaskallInfo.transportTask.charges.businessCharge.itemCharge = "";
      //规则描述
      this.copytaskallInfo.transportTask.ruleRemark = "";
      //全禁用用途
      let carUse = this.dicts.transport_car_use;
      if (carUse && carUse.length) {
        carUse.forEach(carUserItemOld => {
          carUserItemOld.disableState = 1;
        })
      }
      /*判断用途是否为1个，如果为1个用途直接显示出来*/
      let purposeNum = 0;
      let purposeCode = -1;
      if (this.ruleItems) {
        //判断车型code中的用途
        this.ruleItems.forEach(ruleItem => {
          if (ruleItem.dataCode == code) {
            let purpose = ruleItem.purpose;

            //根据用途名放开存在的用途
            for (let k = 0; k < carUse.length; k++) {
              let carUseItem = carUse[k];
              if (carUseItem.dataText.indexOf(purpose) > -1) {
                carUseItem.disableState = 0;
                purposeNum++;
                purposeCode = carUseItem.dataCode;
                this.$forceUpdate()
              }
            }

          }
        })
      }
      if (purposeNum == 1) {
        this.copytaskallInfo.transportTask.transportPurposeCode = purposeCode
        this.changePurposeAsRuleItem(purposeCode)
      }
      this.copytaskallInfo.transportTask.transportCarId = ""
      this.copytaskallInfo.transportTask.driverUserId = ""
      this.copytaskallInfo.transportTask.driverUserTelephone = ""
      //加载车型
      this.loadTransportCar(code, null)

    },//根据用途加规则
    changePurposeAsRuleItem(code) {

      let this_change = this;
      let dataCode = this_change.copytaskallInfo.transportTask.transportCarTypeCode;

      //未选车型
      if (!dataCode) {
        this_change.$message('请先选择预约车型.')
        return;
      }
      let purposeDataCode = code;
      let purpose = "";
      this_change.dicts.transport_car_use.forEach((carUserItem) => {
        if (carUserItem.dataCode == purposeDataCode) {
          purpose = carUserItem.dataText;
        }
      });
      //通过datacode和purpose用途确定规则
      let itemData = this_change.ruleItems;
      if (itemData && itemData.length) {
        for (let k = 0; k < itemData.length; k++) {
          let ruleItem = itemData[k];
          if ((ruleItem.dataCode == dataCode) && ruleItem.purpose.indexOf(purpose) > -1) {
            //服务项目id
            this_change.copytaskallInfo.transportTask.charges.businessCharge.serviceItemId = ruleItem.serviceItemId;
            //服务项目价格
            this_change.copytaskallInfo.transportTask.charges.businessCharge.itemPrice = ruleItem.itemPrice;
            //规则编码
            this_change.copytaskallInfo.transportTask.ruleCode = ruleItem.ruleCode;
            //规则数量
            this_change.copytaskallInfo.transportTask.ruleNumber = ruleItem.itemNumber;
            //计量单位
            this_change.copytaskallInfo.transportTask.ruleUnit = ruleItem.itemUnit;
            //规则描述
            this_change.copytaskallInfo.transportTask.ruleRemark = ruleItem.ruleDescribe;
            // 计算规则编码
            this_change.ruleItem.ruleCode = ruleItem.ruleCode;
            // 计算规则单价
            this_change.ruleItem.itemPrice = ruleItem.itemPrice;
            // 计算规则参数
            this_change.ruleItem.ruleParams = ruleItem.ruleParams;
            this_change.loadChargeWithRule();
            break;
          }
        }
      }

    },
    //计算业务费用调用
    loadChargeWithRule() {
      /*用途为空时返回*/
      let this_load = this;
      if (!this.ruleItem || !this.copytaskallInfo.transportTask.transportPurposeCode) {
        return;
      }
      let ruleData = JSON.parse(this.ruleItem.ruleParams);
      ruleData.itemPrice = this.ruleItem.itemPrice;
      ruleData.transportDistance = this.copytaskallInfo.transportTask.transportDistance;

      let postData = {
        "ruleCode": this.ruleItem.ruleCode,
        "ruleData": JSON.stringify(ruleData)
      }
      Type['loadChargeWithRule'](postData).then(response => {
        let result = response;
        const {data} = result
        if (!data) {
          this.$message('费用计算信息出错.')
        }
        this.copytaskallInfo.transportTask.charges.businessCharge.itemCharge = data.itemCharge;
        //规则编码
        this.copytaskallInfo.transportTask.ruleCode = data.ruleCode;
        //规则数量
        this.copytaskallInfo.transportTask.ruleNumber = data.ruleNumber;
        //计量单位
        this.copytaskallInfo.transportTask.ruleUnit = data.ruleUnit;
        //规则描述
        this.copytaskallInfo.transportTask.ruleRemark = data.ruleRemark;
        this_load.submitFlag = true
        //数据读取成功
      }).catch(error => {
        this.submitFlag
        this_load.$message(error)
        this_load.submitFlag = false
      })
    },
    //触发司机电话号码
    driverUser(id) {
      //司机数据
      let driverData = this.copytaskallInfo.users.transport_task_driver_user;
      if (driverData && driverData.length > 0) {
        let item = null;
        for (let i = 0; i < driverData.length; i++) {
          item = driverData[i];
          if (item.id == id) {
            this.copytaskallInfo.transportTask.driverUserTelephone = item.mobilePhone || item.otherPhone
            break;
          }
        }
      }
    },

    processState(v) {    //任务状态
      if (this.CarryAddFlag) {   //新增时
        this.copytaskallInfo.dicts.transport_car_task_status.forEach(item => {
          if (item.dataText.indexOf("未出车") > -1 || item.dataText.indexOf("已出车") > -1) {
            if (v == item.dataCode) {
              this.$message("新增时任务状态不能为未出车或已出车")
            }
          }
        })
      }
      if (!this.CarryAddFlag) {   //编辑时
        this.copytaskallInfo.dicts.transport_car_task_status.forEach(item => {
          if ((item.dataText.indexOf("未出车") > -1)) {
            if (v == item.dataCode) {
              this.appointmentTimeflag = false
            } else {
              this.appointmentTimeflag = true
            }
          }
        })
      }
    },
    /*判断结算费用是不可结算费用，还是可结算费用*/
    //保存
    Save() {
      //  当前时间和上次点击的时候进行对比，大于2000微秒才执行
      if ((Date.now() - this.onpresscTime) > 2000) {
        this.onpresscTime = Date.now()
        console.log(Date.now())
      } else {
        return
      }
      let processStateCode = typeof this.copytaskallInfo.transportTask.processStateCode == 'number' && this.copytaskallInfo.transportTask.processStateCode >= 0
      let appointmentTime = this.copytaskallInfo.transportTask.appointmentTime
      let transportCarTypeCode = typeof this.copytaskallInfo.transportTask.transportCarTypeCode == 'number' && this.copytaskallInfo.transportTask.transportCarTypeCode >= 0
      let transportPurposeCode = typeof this.copytaskallInfo.transportTask.transportPurposeCode == 'number' && this.copytaskallInfo.transportTask.transportPurposeCode >= 0
      let transportTelephone = this.copytaskallInfo.transportTask.transportTelephone
      let transportPlace = this.copytaskallInfo.transportTask.transportPlace
      if (!processStateCode || !appointmentTime || !transportCarTypeCode || !transportPurposeCode || !transportPlace || !transportTelephone) {
        this.$message('信息未填写完整')
        return;
      }

      this.saveFlag = true;
      let obj = JSON.parse(JSON.stringify(this.copytaskallInfo.transportTask))
      if (obj.charges.goodsServices.length > 0) {

        obj.charges.goodsServices.forEach((item, index) => {
          //业务编码赋值
          item.businessCode = obj.businessCode
          if (item.asSettled == 1) {
            obj.charges.goodsServices.splice(index, 1)
          }
        })
      }

      this.car.forEach(item => {
        //车辆号码
        if (item.id == this.copytaskallInfo.transportTask.transportCarId) {
          obj.transportCarNo = item.carNo
        }

      })
      if (this.copytaskallInfo.users.transport_task_driver_user.length > 0) {
        this.copytaskallInfo.users.transport_task_driver_user.forEach(item => {                 //车辆号码
          if (item.id == this.copytaskallInfo.transportTask.driverUserId) {
            obj.driverUserName = item.fullName
          }
        })
      }

      if (this.CarryAddFlag) {
        obj.appointmentTime = dataFormate(new Date(obj.appointmentTime))
        obj.departureTime = dataFormate(new Date(obj.departureTime))
        obj.returnTime = dataFormate(new Date(obj.returnTime))
        obj.charges.businessCharge.id = 0
        obj.charges.businessCharge.businessCode = 0
        obj.charges.businessCharge.discountCharge = 0
        obj.charges.businessCharge.benefitCharge = 0
        obj.charges.businessCharge.asSettled = 0
        obj.charges.businessCharge.chargeSettleId = 0
        obj.charges.businessCharge.randomCode = 0
        obj.charges.businessCharge.version = 0
        obj.charges.businessCharge.chargeTime = ""
        obj.charges.businessCharge.businessCode = obj.businessCode
        obj.charges.businessCharge.itemCharge = toFixed(this.copytaskallInfo.transportTask.charges.businessCharge.itemCharge, 2)
        obj.charges.businessCharge.realityCharge = this.copytaskallInfo.transportTask.charges.businessCharge.itemCharge

      }
      if (!this.CarryAddFlag) {
        obj.appointmentTime = dataFormate(new Date(obj.appointmentTime));
        obj.departureTime = dataFormate(new Date(obj.departureTime));
        obj.returnTime = dataFormate(new Date(obj.returnTime));

      }
      //服务明细的itemCharge转2位小数
      if (obj.charges.goodsServices.length > 0) {
        obj.charges.goodsServices.forEach((item, index) => {
          item.discountCharge = toFixed(item.discountCharge, 2)
          item.itemCharge = toFixed(item.itemCharge, 2)
          item.itemPrice = toFixed(item.itemPrice, 2)
          item.itemNumber = toFixed(item.itemNumber, 2)
        })
      }
      //验证用途规则
      //可提交标记是true，可以提交，否则，验证未通过，不能提交
      if (this.submitFlag) {
        let postData = obj
        Type['savetransporttask'](postData).then(response => {
          console.log(response)
          let result = response;
          const {data} = result
          if (!data) {
            this.$message('保存信息出错.')
            this.saveFlag = false
            return
          }
          //数据读取成功
          this.taskallInfo.transportTask = data
          this.saveFlag = false;
          this.$message('保存数据成功')
          this.$parent.DialogAddCarry = false
        }).catch(error => {
          this.$message(error)
          this.saveFlag = false;
        })
      } else {
        this.$message.error('数据验证未通过，请确认里程等数据填写正常')
        //保存按钮置为不可提交
        this.saveFlag = false;
        return;
      }

    },

    //追加
    AddRow(index) {
      let row = this.copyGoodServices[index]
      if (index >= 0 && row) {
        row.itemPrice = Number(row.itemPrice).toFixed(2);
        row.itemNumber = Number(row.itemNumber).toFixed(2);
        row.itemCharge = Number((row.itemPrice * row.itemNumber)).toFixed(2);   //计算项目金额
        row.discountCharge = Number(row.discountCharge).toFixed(2);
        let numberValidate = Number(row.itemPrice) >= 0 && Number(row.itemNumber) >= 0 && Number(row.discountCharge) >= 0
        if (!numberValidate || !Number(row.itemCharge) || (Number(row.itemCharge) < Number(row.discountCharge))) {
          this.$message("数值错误，请重新填写")
          Object.assign(row, this.copytaskallInfo.serviceItems.use_in_transport_task[index])
          return true
        }
        // 减免金额
        row.benefitCharge = 0;
        row.asSettled = 0;
        //子项目的serviceItemId=id;
        row.serviceItemId = row.id;
        //新增的id为0
        row.id = 0;

        let list = JSON.parse(JSON.stringify(this.copyGoodServices));
        this.copytaskallInfo.transportTask.charges.goodsServices.push(list[index])
        Object.assign(row, this.copytaskallInfo.serviceItems.use_in_transport_task[index])
      }
    },
    //删除明细行
    deleteRow(index, arry) {
      let _this = this;
      let item = arry[index];
      let itemId = item.id;
      let version = item.version;
      let deleteItem = {"id": itemId, "version": version};
      let deleteItems = _this.copytaskallInfo.transportTask.charges.deleteIds || [];
      if (item && deleteItem.id != 0) {
        //删除的放入删除子项数组
        deleteItems.push(deleteItem);
        //回写删除
        _this.copytaskallInfo.transportTask.charges.deleteIds = deleteItems;
      }
      this.$nextTick(() => {
        //删除服务物品
        _this.copytaskallInfo.transportTask.charges.goodsServices.splice(index, 1);

      })
    },
    closeDialog() {
      this.$parent.DialogAddCarry = false
    },
    filterHandler(value, row, column) {
      // console.log(column)
      const property = column['property'];
      return row[property] === value;
    }

  }, mounted() {
    //按钮权限
    // this.btnRight = this.$route.meta.buttons;
  },
  computed: {
    // tables: function () {
    //   const search = this.search
    //   if (search) {
    //     return this.ruleForm.charges.goodsServices.filter(dataNews => {
    //       return Object.keys(dataNews).some(key => {
    //         return String(dataNews[key]).toLowerCase().indexOf(search) > -1
    //       })
    //     })
    //   }
    //   return this.ruleForm.charges.goodsServices
    // }
  },
}
</script>

<style>

.CarryInfoDialog .el-dialog__title, .CarryInfoDialog .el-dialog__headerbtn .el-dialog__close {
  color: white;
}

.CarryInfoDialog .el-input, .CarryInfoDialog .el-select, .CarryInfoDialog .el-form-item__content {
  width: 200px;
}

.CarryInfoDialog .el-textarea__inner {
  min-width: 200px;
  max-width: 870px;
}

.CarryInfoDialog .el-dialog {
  position: absolute;
  left: 10%;
  z-index: 99999;
}
</style>
<style scoped>
</style>
